//go:build linux
// +build linux

package log

import (
	"fmt"
	"os"
	"path"
	"syscall"
)

func redirect_std_log() error {
	dir := path.Join(path.Dir(os.Args[0]), "..", "log")
	if _, err := os.Stat(dir); err != nil {
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			return err
		}
	}

	std_out_File := path.Join(path.Dir(os.Args[0]), "..", "log", fmt.Sprintf("%s-normal.log", path.Base(os.Args[0])))
	std_err_file := path.Join(path.Dir(os.Args[0]), "..", "log", fmt.Sprintf("%s-error.log", path.Base(os.Args[0])))

	if err := dup_impl(std_out_File, 1); err != nil {
		return err
	}
	if err := dup_impl(std_err_file, 2); err != nil {
		return err
	}
	return nil
}

func dup_impl(filename string, std_fd int) error {
	logFile, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
	if err != nil {
		return err
	}
	err = syscall.Dup2(int(logFile.Fd()), std_fd)
	if err != nil {
		return err
	}
	return nil
}
